# encoding: utf-8

import xadmin
from xadmin import views
from .models import *
from django import forms
#from .forms import *
from usercenter.models import Users
#from .models import xbRoom
from xadmin.layout import Main, TabHolder, Tab, Fieldset, Row, Col, AppendedText, Side
from xadmin.plugins.inline import Inline
from xadmin.plugins.batch import BatchChangeAction
from django.utils.translation import ugettext_lazy as _
import logging
logger = logging.getLogger(__name__)
from django.conf import settings
import datetime
from django.http import HttpResponseRedirect 


class MyLoginView(object):
  title= u'会议管理系统 请登录'

xadmin.site.register(views.website.LoginView, MyLoginView)

class MainDashboard(object):
    #menu_template = 'xadmin/includes/sitemenu_forxb.html'
    #widgets = [
    #    [
           # {"type": "html", "title": "小提示", "content": "<h3> 您好欢迎使用会议室预约系统! </h3><p>预约会议室，您可以点击左侧的‘预订会议室’ <br/></p>"},
            #{"type": "chart", "model": "app.accessrecord", 'chart': 'user_count', 'params': {'_p_date__gte': '2013-01-08', 'p': 1, '_p_date__lt': '2013-01-29'}},
           # {"type": "roomlist", "model": "yudingapp.xbRoom", 'params': {
           #     'o':'-create_time'}},
     #   ],
      #  [
      #      {"type": "qbutton", "title": "Quick Start", "btns": [{'model': Host}, {'model':IDC}, {'title': "Google", 'url': "http://www.google.com"}]},
      #      {"type": "addform", "model": MaintainLog},
      #  ]
    #]
    site_title=u'会议室管理系统'
    
xadmin.site.register(views.website.IndexView, MainDashboard)




#-------------------------------------------------
class xbRoomAdmin(object):
  list_display = ('name','brief','photo','xiaoqu','location','status','telphone','create_time')
  list_display_links = ('name',)
  reversion_enable = True
  search_fields = ['name',]
  #object_list_template="xadmin/views/rchf_model_room_list.html"

xadmin.site.register(xbRoom,xbRoomAdmin)




class yudingTimeAdmin(object):
  list_display = ('id','name','status')
  list_display_links = ('name',)
  reversion_enable = True
  search_fields = ['name',]
  list_filter=('status',)


xadmin.site.register(yudingTime,yudingTimeAdmin)


#-------------------
#审核相关函数设置
#-------------------
#审核基础
def make_shenhe_base(modeladmin, request, queryset,ydStatusNum,msg):
    if request.user.is_superuser:
      #return HttpResponseRedirect("https://www.baidu.cn")
      myuser=Users.objects.get(user__id=request.user.id)
      queryset.update(ydStatus=ydStatusNum,spUser=myuser,shenpi_time=datetime.datetime.now())
      modeladmin.message_user(msg['success'],'success')
    else:
      myuser=Users.objects.get(user__id=request.user.id)
      pcheck=myuser.user_type.filter(permission__key='quanxian_yuding_shenpi')
      if len(pcheck)>0:
        queryset.update(ydStatus=ydStatusNum,spUser=myuser,shenpi_time=datetime.datetime.now())
        modeladmin.message_user(msg['success'],'success')
      else:
        modeladmin.message_user(msg['warning'],'warning')





#---------------------------
#设置为待审核
def make_shenhe_dengdai(modeladmin, request, queryset):
    #return HttpResponseRedirect("https://www.baidu.cn")
    msg={}
    msg['success']=u'恭喜审批完成 '+str(len(queryset))+u' 项'
    msg['warning']=u'抱歉您没有审批权限，请联系管理员'
    make_shenhe_base(modeladmin, request, queryset,0,msg)

make_shenhe_dengdai.short_description = "设置为待审核"

#设置为审核通过
def make_shenhe_tongguo(modeladmin, request, queryset):
    msg={}
    msg['success']=u'恭喜审批完成 '+str(len(queryset))+u' 项'
    msg['warning']=u'抱歉您没有审批权限，请联系管理员'
    make_shenhe_base(modeladmin, request, queryset,1,msg)

make_shenhe_tongguo.short_description = "设置为审核通过"


#设置为审核不通过
def make_shenhe_butongguo(modeladmin, request, queryset):
    msg={}
    msg['success']=u'设置完成 '+str(len(queryset))+u' 项为审核未通过'
    msg['warning']=u'抱歉您没有审批权限，请联系管理员'
    make_shenhe_base(modeladmin, request, queryset,20,msg)

make_shenhe_butongguo.short_description = "设置为审核未通过"

#----------------------
#发送短信
import sms
def  send_sms_status(queryset):
    sms_msg=u'公大会议系统:'
    for item in queryset:
      sms_msg=sms_msg+item.ydUser.user_name+u' 您好，您预订的 '+item.ydRoom.name +' '+Yuding_STATUS_DIC[str(item.ydStatus)]
      cstr=sms_msg
      tel=item.ydUser.user_mobilephone
      sms.sendsms(tel,cstr)

def action_sms_tongzhi(modeladmin, request, queryset):
    #return HttpResponseRedirect("https://www.baidu.cn")
    #paradic={'smsStatus':'1',}
    #permissionDic={'key':'quanxian_sms_tongzhi'}

    msg={}
    msg['success']=u'恭喜已通知 '+str(len(queryset))+u' 项'
    msg['warning']=u'抱歉您没有短信通知，请联系管理员'
    #make_shenhe_base(modeladmin, request, queryset,paradic,msg)
    if request.user.is_superuser:
      #return HttpResponseRedirect("https://www.baidu.cn")
      #myuser=Users.objects.get(user__id=request.user.id)
      send_sms_status(queryset)
      queryset.update(smsStatus=1)
      modeladmin.message_user(msg['success'],'success')
    else:
      myuser=Users.objects.get(user__id=request.user.id)
      pcheck=myuser.user_type.filter(permission__key='quanxian_sms_tongzhi')
      if len(pcheck)>0:
        #queryset.update(ydStatus=ydStatusNum,spUser=myuser,shenpi_time=datetime.datetime.now())
        send_sms_status(queryset)
        queryset.update(smsStatus=1)
        modeladmin.message_user(msg['success'],'success')
      else:
        modeladmin.message_user(msg['warning'],'warning')


action_sms_tongzhi.short_description = "短信通知"

#-------------------------------------------

class yudingAdmin(object):
  list_display = ('ydRoom','ydUser','ydDate','ydTime','color_ydStatus','spUser','shenpi_time','smsStatus','beizhu')
  reversion_enable = True
  search_fields = ['ydRoom','ydUser',]
  list_filter=("ydStatus",'ydDate',)

  def color_ydStatus(self,obj):
    indexNum=obj.ydStatus
    if obj.ydStatus==0:
      return '<span class="label label-warning">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])
    if obj.ydStatus==1:
      return '<span class="label label-success">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])
    if obj.ydStatus==20:
      return '<span class="label label-danger">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])


  color_ydStatus.allow_tags = True
  color_ydStatus.short_description = "预订状态"



  actions=[make_shenhe_tongguo,make_shenhe_butongguo,action_sms_tongzhi,make_shenhe_dengdai,] 


xadmin.site.register(yuding,yudingAdmin)



#-----------------------------------
#代理操作
#-----------------------------------
class yulan_RoomAdmin(object):
  list_display = ('name','brief','photo','xiaoqu','location','status','telphone','create_time')
  list_display_links = ('name',)
  reversion_enable = True
  search_fields = ['name',]
  list_filter=("status",'xiaoqu',)
  object_list_template="xadmin/views/rchf_model_room_list.html"
  add_form_template="xadmin/views/rchf_model_room_form.html"

xadmin.site.register(yulan_Room,yulan_RoomAdmin)

#-----------------------------------------------


#----------------------------------------------
# coding: utf-8

def getydTimeByUser(ydUser,ydDate):

  #nydDate = datetime.strptime(ydDate, "%Y-%m-%d")
  readyTimes=yuding.objects.filter(ydDate=ydDate)
  idkeys=[]
  for yudingItem in readyTimes:
    for item in yudingItem.ydTime.values():
      idkeys.append(item['id'])

  ydAll= yudingTime.objects.exclude(id__in= idkeys)
  return ydAll

#----------------------------------------------
class yulan_YudingAdmin(object):
  list_display = ('ydRoom','ydUser','ydDate','ydTime','color_ydStatus')
  #list_display_links = ('name',)
  reversion_enable = True
  search_fields = ['name',]
  wizard_form_list = [
        (u'第一步', ('ydRoom','ydDate',)),
        (u'第二步', ('ydTime',)),
        #('Thread Form', ('customer_id',))
  ]
  style_fields = {'ydTime': 'm2m_transfer'}

  #filter_horizontal = ('ydTime',)
  search_fields = ['name']
  relfield_style = 'fk-ajax'

  def formfield_for_dbfield(self, db_field, **kwargs):
    logger.info('-------- '+'db_field.name'+' ------')
    if 'ydTime' == db_field.name :
      field = super(yulan_YudingAdmin, self).formfield_for_dbfield(db_field, **kwargs)
      ydDate=self.request.POST.get(u'step_0-ydDate', None)
      if ydDate is not None:
        self.request.session['ydDate']=ydDate
        qset=getydTimeByUser(self.user,ydDate)
        field.queryset=qset
        if len(qset)==0:
          field.help_text=_("抱歉该会议室没有时段可预约，请更换预订日期")
        else:
          field.help_text=_("请选择预约时段，")
      else:
        gydDate=self.request.session['ydDate']
        field.queryset=getydTimeByUser(self.user,gydDate)

      return field

    field = super(yulan_YudingAdmin, self).formfield_for_dbfield(db_field, **kwargs)
    return field

  def save_models(self):
    #logger.info('-------- '+'save_models'+' ------')
    #logger.info(self.request.POST)
    secondform=self.request.POST.get(u'yudingappyulan_yuding_admin_wizard_form_plugin-current_step',None)
    logger.info(secondform)
    if (secondform is not None) & (secondform==u'第二步'):
      #logger.info('-----section form----------')
      #logger.info(self.new_obj)
      #self.new_obj
      obj = self.new_obj
      myuser=Users.objects.get(user__id=self.user.id)
      obj.ydUser=myuser
      obj.ydStatus=0
      obj.save()
 

  def queryset(self):
    qs = super(yulan_YudingAdmin, self).queryset()
    #print self.user
    if self.user.is_superuser:  
        #return qs
        return qs.filter(ydDate__gte=datetime.date.today())
    else:
      myuser=Users.objects.get(user__id=self.user.id)
      return qs.filter(ydUser=myuser,ydDate__gte=datetime.date.today())

  def delete_models(self, queryset):
    for obj in queryset:
      if obj.ydStatus==1:
        self.message_user(u'抱歉,审批通过的预订记录无法删除，您可以联系管理员进行删除','warning')
        return 
    
    super(yulan_YudingAdmin, self).delete_models(queryset)

  def color_ydStatus(self,obj):
    indexNum=obj.ydStatus
    if obj.ydStatus==0:
      return '<span class="label label-warning">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])
    if obj.ydStatus==1:
      return '<span class="label label-success">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])
    if obj.ydStatus==20:
      return '<span class="label label-danger">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])


  color_ydStatus.allow_tags = True
  color_ydStatus.short_description = "预订状态"


xadmin.site.register(yulan_Yuding,yulan_YudingAdmin)




#-------------------
class shenpi_YudingAdmin(object):
  list_display = ('ydRoom','ydUser','ydDate','ydTime','ydStatus','shenpi_time','beizhu','smsStatus')
  reversion_enable = True
  search_fields = ['ydRoom',]

  def queryset(self):
    return super(shenpi_YudingAdmin, self).queryset().filter(ydStatus=0,ydDate__gte=datetime.date.today())

  actions=[make_shenhe_tongguo,make_shenhe_butongguo,make_shenhe_dengdai,action_sms_tongzhi,]

xadmin.site.register(shenpi_Yuding,shenpi_YudingAdmin)


#-------------------
class jinri_YudingAdmin(object):
  list_display = ('ydRoom','ydUser','ydDate','ydTime','color_ydStatus','shenpi_time','beizhu','spUser','smsStatus')
  reversion_enable = True
  search_fields = ['ydRoom','ydUser','ydTime',]
  list_filter=("ydRoom",'ydTime',)
  #ordering =['-ydDate']

  def color_ydStatus(self,obj):
    indexNum=obj.ydStatus
    if obj.ydStatus==0:
      return '<span class="label label-warning">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])
    if obj.ydStatus==1:
      return '<span class="label label-success">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])
    if obj.ydStatus==20:
      return '<span class="label label-danger">%s</span>'%(Yuding_STATUS_DIC[str(indexNum)])


  color_ydStatus.allow_tags = True
  color_ydStatus.short_description = "预订状态"

  def queryset(self):
    return super(jinri_YudingAdmin, self).queryset().filter(ydDate=datetime.date.today())

  actions=[action_sms_tongzhi,]

xadmin.site.register(jinri_Yuding,jinri_YudingAdmin)







